package com.wbao.dianniu.im;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.wbao.dianniu.R;
import com.wbao.dianniu.data.HeadData;
import com.wbao.dianniu.indexView.CharacterParser;
import com.wbao.dianniu.indexView.PinyinComparator;
import com.wbao.dianniu.indexView.SideBar;
import com.wbao.dianniu.indexView.SideBar.OnTouchingLetterChangedListener;
import com.wbao.dianniu.indexView.SortAdapter;
import com.wbao.dianniu.indexView.SortModel;
import com.wbao.dianniu.listener.IFriendListListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.FriendListManager;
import com.wbao.dianniu.update.ShareSDKManager;
import com.wbao.dianniu.ui.BaseActivity;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 通讯录
 *
 * @author yejianjun
 */
public class ConversationBook2 extends BaseActivity implements OnClickListener, IFriendListListener {
    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;
    private SideBar sideBar;
    private TextView dialog;
    private SortAdapter adapter;
    private ListView sortListView;
    private FriendListManager manager;

    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<SortModel> SourceDateList;
    private LinearLayout mFollow;
    private LinearLayout addFriends;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private Button addFriendBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.fragment_friends, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        setTitleName("通讯录");
        initWattingView();
        initView();
        initData();
    }

    private void initWattingView() {
        waittingLayout = (LinearLayout) findViewById(R.id.waitting_layout);
        waittingProBar = (ProgressBar) findViewById(R.id.waitting_progress);
        waittingTV = (TextView) findViewById(R.id.waitting_text_desc);
    }

    private void initData() {
        manager = new FriendListManager(this);
        manager.addFriendListener(this);
        manager.friendList(GlobalContext.getAccountId(), 0, 999);
    }

    private void initView() {
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        //SourceDateList = filledData(getResources().getStringArray(R.array.date));
        SourceDateList = new ArrayList<SortModel>();
        adapter = new SortAdapter(this, SourceDateList);
        // 根据a-z进行排序源数据
        Collections.sort(SourceDateList, pinyinComparator);

        sideBar = (SideBar) findViewById(R.id.sidrbar);
        dialog = (TextView) findViewById(R.id.choose_indext_dialog);
        mFollow = (LinearLayout) findViewById(R.id.follow_linearlayout);
        addFriends = (LinearLayout) findViewById(R.id.add_friend_injoin);
        //我的关注
        mFollow.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra(Const.INTENT_ID, GlobalContext.getAccountId());
                intent.setClass(ConversationBook2.this, FollowListActivity.class);
                startActivity(intent);
            }
        });
        //邀请好友加入
        addFriends.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
                shareSDKManager.showShare(ConversationBook2.this, "我正在玩电纽，打造自己的电商圈，您也赶快加入吧！", 3, GlobalContext.cdndownUrl + "logo.png", GlobalContext.getAccountId());
            }
        });

        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }
            }
        });
        sideBar.setTextView(dialog);
        sortListView = (ListView) findViewById(R.id.country_lvcountry);
        sortListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //这里要利用adapter.getItem(position)来获取当前position所对应的对象
                Integer accountId = ((SortModel) adapter.getItem(position)).getFriendId();
                Utils.intoHeadInfoActivity(accountId, ConversationBook2.this);
            }
        });
        sortListView.setAdapter(adapter);
        addFriendBtn = getRightTextButton();
        addFriendBtn.setText(getResources().getString(R.string.add_friend_title));
        addFriendBtn.setOnClickListener(this);
    }

    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    private List<SortModel> filledData(HeadData[] date) {
        List<SortModel> mSortList = new ArrayList<SortModel>();

        for (int i = 0; i < date.length; i++) {
            SortModel sortModel = new SortModel();
//			sortModel.setAccountId(date[i].accountId);
            sortModel.setName(date[i].realName);
            sortModel.setFriendId(date[i].friendId);
            sortModel.setSex(date[i].sex);
            sortModel.setIndustryAuthority(date[i].isIndustryAuthority);
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(date[i].realName);
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }
            sortModel.setLabel(date[i].label);
            sortModel.setUrl(date[i].headPic);
            mSortList.add(sortModel);
        }
        return mSortList;

    }

    @Override
    public void onFriendFailure(int errorCode, String errorMsg) {
        // TODO Auto-generated method stub
        waittingLayout.setVisibility(View.VISIBLE);
        waittingProBar.setVisibility(View.GONE);
        waittingTV.setText("加载失败，请稍后再试...");
    }

    @Override
    public void onFriendSuccess(List<HeadData> objdata) {
        waittingLayout.setVisibility(View.GONE);
        if (null == objdata) {
            return;
        }
        HeadData[] heads = new HeadData[objdata.size()];
        for (int i = 0; i < heads.length; i++) {
            heads[i] = new HeadData();
            heads[i].headPic = objdata.get(i).headPic;
            heads[i].label = objdata.get(i).label;
            heads[i].realName = objdata.get(i).realName;
            heads[i].friendId = objdata.get(i).friendId;
            heads[i].sex = objdata.get(i).sex;
            heads[i].isIndustryAuthority = objdata.get(i).isIndustryAuthority;
        }
        SourceDateList = filledData(heads);
        adapter.updateListView(SourceDateList);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.right_button:
                // 加好友列表
                Intent intent = new Intent();
                intent.setClass(ConversationBook2.this, AddFriendActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeFriendListener(this);
        }
    }
}
